const {
	Service
} = require("uni-cloud-router");
const {
	result_success,
	result_error
} = require('http-result-modle');
const {
	checkToken
} = require('common-uni-id');
const db = uniCloud.database();
const wmzSoundSdk = uniCloud.importObject('wmz-sound-sdk')
module.exports = class GatheringService extends(
	Service
) {

	async orderPay(event) {
		let params;
		if (event.params) {
			params = event.params;
		} else if (event.data) {
			params = event.data;
		} else {
			return result_error('参数丢失', null);
		}
		if (!params) {
			return result_error('参数丢失', null);
		}
		if (!params.appId) {
			return result_error('应用id参数不能为空', null);
		}
		if (!params.shopId) {
			return result_error('门店id参数不能为空', null);
		}
		if (!params.payWay) {
			params.payWay = '支付宝'
		}
		if ('' === params.payMoney || null === params.payMoney || undefined === params.payMoney || 0 ===
			parseFloat(params.payMoney)) {
			return result_error('支付金额参数不能为空', null);
		}
		if (!params.authPlatform) {
			params.authPlatform = 'alipay'
		}
		let appId = params.appId;
		let shopId = params.shopId;
		let templateId = params.templateId
		let authCode = params.authCode;
		let authPlatform = params.authPlatform;
		let payWay = params.payWay;
		let payMoney = parseFloat(params.payMoney) * 100;

		let methodName;
		if ('alipay' === authPlatform) {
			methodName = '/member/loginByAlipay';
		} else if ('wechat' === authPlatform) {
			methodName = '/member/loginByWeixin';
		} else {
			return result_error('用户授权平台参数不正确', null);
		}

		let userInfo = null;
		let balanceMoney = 0;
		let consumeMoney = 0;
		let memberRes
		if (this.ctx.event.uniIdToken) {
			const userRes = await checkToken(this.ctx.event.uniIdToken);
			if (userRes.userInfo) {
				userInfo = userRes.userInfo;

				let queryMember = {
					_id: userInfo._id
				};

				memberRes = await db.collection('wmzmall-member').where(queryMember).orderBy("create_time",
					"desc").limit(1).get();
				if (memberRes && memberRes.data && memberRes.data.length > 0) {
					memberRes = memberRes.data[0];
					if (memberRes.member_amount) {
						balanceMoney = parseFloat(memberRes.member_amount);
					}
					if (memberRes.member_monetary) {
						consumeMoney = parseFloat(memberRes.member_monetary);
					}
				}
			}
		}
		if (!userInfo) {
			let loginRes = await uniCloud.callFunction({
				name: "wmzmall",
				data: {
					path: methodName,
					data: {
						app_id: appId,
						shop_id: shopId,
						code: authCode,
						templateId: templateId
					}
				}
			});

			if (!loginRes || !loginRes.result || !loginRes.result.user || !loginRes.result.user.userInfo) {
				return result_error('登录失败，请关闭小程序进程扫码重试', null);
			}

			userInfo = loginRes.result.user.userInfo;

			if (loginRes && loginRes.result && loginRes.result.member) {
				let member = loginRes.result.member;

				if (member.member_amount) {
					balanceMoney = parseFloat(member.member_amount);
				}
				if (member.member_monetary) {
					consumeMoney = parseFloat(member.member_monetary);
				}
			}
		}
		if (!userInfo || !userInfo.openid) {
			return result_error('未查询到用户信息', null);
		}
		appId = userInfo.app_id
		shopId = userInfo.shop_id
		const config = this.service.utils.getConfig();

		let orderNo = ('wmg_order_' + new Date().getTime() + (Math.round(Math.random() * 1000000) + '')
			.padStart(6, '0'));
		let payId = ('wmg_pay_' + new Date().getTime() + (Math.round(Math.random() * 1000000) + '').padStart(6,
			'0'));
		let payTitle = `${config.appname}-` + '收款码支付';
		let openid = userInfo.openid;
		let notifyUrl = '/notify-gathering';
		let vip_price_discount = 0
		if (memberRes.vip_price_discount && payMoney >= 100) {
			vip_price_discount = (payMoney - payMoney * memberRes.vip_price_discount);
			payMoney = payMoney - vip_price_discount;
		}
		let gatheringOrder = {
			app_id: appId,
			shop_id: shopId,
			order_no: orderNo,
			order_pay_no: null,
			order_pay_way: payWay,
			order_pay_state: '待付款',
			order_pay_time: null,
			order_total_money: payMoney,
			order_surplus_money: payMoney,
			order_pay_money: payMoney - balanceMoney - vip_price_discount,
			order_actually_pay: payMoney - balanceMoney - vip_price_discount,
			order_actually_income: payMoney,
			order_balance_money: balanceMoney,
			vip_price_discount: vip_price_discount,
			order_third_discount: null,
			order_coupon: null,
			order_coupon_id: null,
			order_coupon_money: null,
			order_coupon_name: null,
			order_coupon_json: null,
			order_refund_money: null,
			order_refund_state: null,
			order_refund_reason: null,
			order_refund_desc: null,
			remark: null,
			state: '待付款',
			is_delete: 0,
			create_time: new Date().getTime(),
			create_uid: userInfo._id ? userInfo._id : null,
			create_uname: userInfo.username ? userInfo.username : null,
			delete_time: null,
			delete_uid: null,
			delete_uname: null
		};

		let gatheringPay = {
			app_id: appId,
			shop_id: shopId,
			order_no: orderNo,
			pay_openid: openid,
			pay_money: payMoney,
			pay_title: payTitle,
			pay_way: payWay,
			pay_original: null,
			pay_trade_type: 'JSAPI',
			pay_id: payId,
			pay_pre_id: null,
			pay_res: null,
			pay_time: null,
			pay_notify: null,
			pay_state: '待付款',
			version: 1,
			is_delete: 0,
			create_time: new Date().getTime(),
			create_uid: userInfo._id ? userInfo._id : null,
			create_uname: userInfo.username ? userInfo.username : null
		};

		let payOrderInfo;
		switch (payWay) {
			case '支付宝':

				let alipayOrderInfo = await this.service.alipay.pay(userInfo.app_id, openid, orderNo, payMoney,
					payTitle, notifyUrl + '/alipay');
				gatheringPay.pay_res = JSON.stringify(alipayOrderInfo);

				uniCloud.logger.info("alipayOrderInfo: ", gatheringPay.pay_res);

				if (!alipayOrderInfo.data) {
					return result_error(alipayOrderInfo.data || '获取支付宝支付订单号失败', null);
				}

				gatheringPay.pay_original = '支付宝支付';
				gatheringPay.pay_pre_id = alipayOrderInfo.prepayId;
				payOrderInfo = {
					trade_no: alipayOrderInfo.data
				};

				break;
			case '微信支付':

				let wechatOrderInfo = await this.service.wechat.pay(appId, openid, orderNo, payMoney, payTitle,
					notifyUrl + '/wechat');
				gatheringPay.pay_res = JSON.stringify(wechatOrderInfo);

				if (!wechatOrderInfo.data.package) {
					return result_error('获取微信支付订单配置失败', null);
				}

				gatheringPay.pay_original = '微信支付';
				gatheringPay.pay_pre_id = wechatOrderInfo.data.package;
				payOrderInfo = wechatOrderInfo.data;
				break;
			case '余额支付':

				if (0 >= balanceMoney) {
					return result_error('您暂无余额可以抵扣', null);
				}
				if (payMoney > balanceMoney) {
					return result_error('您当前余额不足，不够抵扣支付金额', null);
				}

				let datetime = new Date().getTime();

				gatheringOrder.order_pay_state = '已付款';
				gatheringOrder.pay_time = datetime;
				gatheringOrder.state = '已完成';

				gatheringPay.pay_time = datetime;
				gatheringPay.pay_state = '已付款';

				break;
			default:
				return result_error('支付方式参数不正确', null);
		}

		payOrderInfo.pay_id = payId;

		const transaction = await db.startTransaction();

		try {

			let addOrderResult = await transaction.collection('wmzmall-gathering-order').add(gatheringOrder);
			if (!addOrderResult || !addOrderResult.id) {
				return result_error('新增收款码订单数据失败', null);
			}

			let addPayResult = await transaction.collection('wmzmall-gathering-pay').add(gatheringPay);
			if (!addPayResult || !addPayResult.id) {
				return result_error('新增收款码支付数据失败', null);
			}

			if ('余额支付' === payWay) {
				let memberBalance = {
					member_amount: balanceMoney - payMoney,
					member_monetary: consumeMoney + payMoney
				};

				let updateResult = await transaction.collection('wmzmall-member').doc(userInfo._id).update(
					memberBalance);
				if (!updateResult) {
					return result_error('更新会员余额数据失败', null);
				}

				let title = '收款码收款';
				let cate = '收款码收款';
				let type = 0;
				let way = '余额支付';

				let shopieRes = await this.service.shopie.cloudAddShopie(appId, shopId, orderNo, title, cate,
					type, way, payMoney);
				if (!shopieRes || !shopieRes.datas || !shopieRes.datas.data) {
					let errMsg = '新增收支数据失败';

					if (shopieRes && shopieRes.msg) {
						errMsg = shopieRes.msg;
					}

					return result_error(errMsg, null);
				}
			}

			await transaction.commit();

		} catch (e) {
			await transaction.rollback();
			console.error(`transaction error`, e);
		} finally {
			console.log("payOrderInfo")
			console.log(payOrderInfo)
			return result_success(payOrderInfo, '收款码下单支付成功');
		}
	}


	async orderCancel(event) {
		let params;
		if (event.params) {
			params = event.params;
		} else if (event.data) {
			params = event.data;
		} else {
			return result_error('参数丢失', null);
		}
		if (!params) {
			return result_error('参数丢失', null);
		}
		if (!params.shopId) {
			return result_error('门店id参数不能为空', null);
		}
		let soundData = await db.collection('wmzmall-sound').where({
			shop_id: params.shopId,
			cancel: '播报'
		}).get()
		soundData = soundData.data
		if (soundData && soundData.length > 0) {
			for (var i in soundData) {
				await wmzSoundSdk.play({
					device_code: soundData[i].device_code,
					content: params.money + '元已取消付款'
				})
			}
		}
		return result_success();
	}
};